package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.Merchant;
import com.turing.post.organization.util.MerchantBusiness;
import com.turing.post.organization.util.MerchantContract;
import com.turing.post.organization.util.MerchantContractDao;
import com.turing.post.organization.util.MerchantDao;
import com.turing.post.organization.util.OrganApplicationException;
import com.turing.post.organization.util.OrganRespCode;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * @author zxp
 * @Dec 19, 2012
 */
@Stateless(mappedName = "organization.impl.MerchantBusinessImpl")
@Remote
@Local
public class MerchantBusinessImpl implements MerchantBusiness {

	@EJB(mappedName = "organization.impl.MerchantDaoImpl")
	private MerchantDao merchantDaoImpl;

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao sysBranchDaoImpl;

	@EJB(mappedName = "organization.impl.MerchantContractDaoImpl")
	private MerchantContractDao mctDaoImpl;

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;

	// 新增特约商户（Merchant）
	@Override
	public void insertMerchantInfo(PCPSWebInput webInput, Merchant merchant)
			throws PCPSApplicationException {
		// 登录用户机构号为空
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "登录用户机构号为NULL");
		}
		// 检查逻辑
		if (merchant == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"merchant");
		}
		// 编号
		if (PCPSUtil.isEmpty(merchant.getMerchantNo())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"MerchantNo");
		}
		// 名称
		if (PCPSUtil.isEmpty(merchant.getMerchantName())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"商户名称为空!");
		}
		// 单笔消费上限
		if (merchant.getEachPaidLimit() == null
				|| merchant.getEachPaidLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"单笔消费上限为空或小于0!");
		}
		// 商户单笔充值上限不能大于发卡商商户交易单笔充值上限
		// if(merchant.getAllowDeposit().equals(Merchant.MERCHANT_ALLOW_DEPOSIT)){
		IssueCompany company = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(webInput.getOperBranchNo()
						.substring(0, 6));
		if (company.getMrchEachDepositLimit().intValue() < merchant
				.getEachDepositLimit().intValue()) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"商户单笔充值上限不能大于发卡商商户交易单笔充值上限!");
		}
		if (merchant.getDepositLimit().intValue() < merchant
				.getEachDepositLimit().intValue()) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"单笔充值上限不能大于充值额度上限!");
		}
		// }
		// 当日累计消费金额上限
		if (merchant.getDayPaidTotalLimit() == null
				|| merchant.getDayPaidTotalLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"当日累计消费金额上限为空或小于0!");
		}
		// 当日累计消费次数上限
		if (merchant.getDayPaidCountLimit() == null
				|| merchant.getDayPaidCountLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"当日累计消费次数上限为空或小于0!");
		}
		// 名称
		if (PCPSUtil.isEmpty(merchant.getRegionNo())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"行政区域为空!");
		}
		// 编号是否存在
		if (merchantDaoImpl.getMerchantByMerchantNo(merchant.getMerchantNo()) != null) {
			throw new OrganApplicationException(OrganRespCode.BRANCHNO_EXIST,
					"商户编号已经存在!");
		}
		// 归属发卡商
		merchant.setIssueCompanyNo(merchant.getMerchantNo().substring(0, 6));
		// 账务日期
		IssueCompany ic = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(merchant.getMerchantNo()
						.substring(0, 6));
		merchant.setTranDate(ic.getTranDate());
		// 交易状态
		merchant.setTranStatus(Merchant.MERCHANT_TRANSTATUS);
		// 流水顺序号
		merchant.setTranSeqNo(BigInteger.ZERO);
		// 当前余额
		merchant.setBalance(BigInteger.ZERO);
		// 验证发商户编号是否已经使用
		if (merchantDaoImpl.getMerchantByMerchantNo(merchant.getMerchantNo()) != null) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					"商户编号已经存在!");
		}

		// 平台机构管理员归属机构号为空
		if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			if (!PCPSUtil.getIssueCompanyNo(webInput).equals(
					merchant.getMerchantNo().substring(0, 6)))
				throw new OrganApplicationException(
						OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
						OrganRespCode.ISSUE_INSERT_UPDATE, "无权添加其他发卡商下商户!");
		}
		if (merchantDaoImpl.IsMerchantName(merchant.getIssueCompanyNo(),
				merchant.getMerchantName(), "") > 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					merchant.getMerchantName() + ":已经存在");
		}
		// 如果选择允许充值,并且按周期总充值额控制时,充值上限必须>0
		if (merchant.getAllowDeposit().equals("1")
				&& "0".equals(merchant.getDepositLimitType())) {
			if (merchant.getDepositLimit().compareTo(BigInteger.ZERO) <= 0) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"充值额度上限必须大于0");
			}
			// SaleBranch saleBranch = saleBranchDaoImpl
			// .getSaleBranchBySaleBranchNo(merchant
			// .getDepositSaleBranchNo());
			// if (saleBranch == null) {
			// throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
			// "充值归属销售机构不存在！");
			// }
		}

		if (PCPSUtil.isEmpty(merchant.getTranKey())) {
			merchant.setTranKey("00000000");// 密钥
		}

		// 保证金不能小于0
		if (merchant.getGuaranteeAmount().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"商户保证金不能小于0！");
		}
		// 预付款下限不能小于0
		if (merchant.getPrepaidLowLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"预付款提醒下限不能小于0！");
		}

		// 插入平台机构主键表数据
		SysBranch sysBranch = new SysBranch(merchant.getMerchantNo(),
				SysBranch.SYSBRANCH_MERCHANT);
		sysBranchDaoImpl.insertSysBranch(sysBranch);
		// 插入商户表
		merchantDaoImpl.insertMerchant(merchant);
		// 插入数据库操作日志
		insertRecordingOperationLog(webInput, "创建商户", merchant,
				SysOperLog.operType_Add, "MerchantName:"
						+ merchant.getMerchantName());
	}

	/**
	 * 查询锁定表进行修改
	 */
	@Override
	public void updateMerchantInfo(PCPSWebInput webInput, Merchant merchant)
			throws PCPSApplicationException {
		// 登录用户机构号为空
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "登录用户机构号为NULL");
		}
		Merchant _merchant = merchantDaoImpl.getMerchantForUpdate(merchant
				.getMerchantNo());
		// 检查逻辑
		if (_merchant == null) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "待修改商户数据库不存在!");
		}
		// 单笔消费上限
		if (merchant.getEachPaidLimit() == null
				|| merchant.getEachPaidLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"单笔消费上限为空或小于0!");
		}

		// 检查此商户的合同结算策略是否为:按业务类型
		List<MerchantContract> mcList = mctDaoImpl
				.checkMerchantContractNeedBusinessByMrchNo(merchant
						.getMerchantNo());
		if (!Merchant.BUSINESSTYPE_NEED.equals(merchant.getNeedBusinessType())
				&& mcList != null && mcList.size() > 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"当前此商户的合同结算策略为:按商业类型结算,此商户需要业务类型!");
		}

		// 商户单笔充值上限不能大于发卡商商户交易单笔充值上限
		// if(merchant.getAllowDeposit().equals(Merchant.MERCHANT_ALLOW_DEPOSIT)){
		IssueCompany company = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(webInput.getOperBranchNo()
						.substring(0, 6));
		if (company.getMrchEachDepositLimit().intValue() < merchant
				.getEachDepositLimit().intValue()) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"商户单笔充值上限不能大于发卡商商户交易单笔充值上限!");
		}
		if (merchant.getDepositLimit().intValue() < merchant
				.getEachDepositLimit().intValue()) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"单笔充值上限不能大于充值额度上限!");
		}
		// }
		// 当日累计消费金额上限
		if (merchant.getDayPaidTotalLimit() == null
				|| merchant.getDayPaidTotalLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"当日累计消费金额上限为空或小于0!");
		}
		// 当日累计消费次数上限
		if (merchant.getDayPaidCountLimit() == null
				|| merchant.getDayPaidCountLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"当日累计消费次数上限为空或小于0!");
		}
		// 保证金不能小于0
		if (merchant.getGuaranteeAmount().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"商户保证金不能小于0！");
		}
		// 预付款下限不能小于0
		if (merchant.getPrepaidLowLimit().compareTo(BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"预付款提醒下限不能小于0！");
		}
		// 对象赋值
		_merchant.setMerchantName(merchant.getMerchantName());
		// _merchant.setMerchantTypeId(merchant.getMerchantTypeId());
		_merchant.setIncomeBranchId(merchant.getIncomeBranchId());
		_merchant.setActivate(merchant.getActivate());
		_merchant.setCheckAccMode(merchant.getCheckAccMode());
		_merchant.setNeedBusinessType(merchant.getNeedBusinessType());
		_merchant.setChannelMode(merchant.getChannelMode());
		_merchant.setLinkMan(merchant.getLinkMan());
		_merchant.setLinkTele(merchant.getLinkTele());
		_merchant.setAllowDeposit(merchant.getAllowDeposit());
		_merchant.setDepositLimit(merchant.getDepositLimit());
		_merchant.setDepositLimitType(merchant.getDepositLimitType());
		_merchant.setDepositLimitCycle(merchant.getDepositLimitCycle());
		_merchant.setEachDepositLimit(merchant.getEachDepositLimit());
		_merchant.setEachPaidLimit(merchant.getEachPaidLimit());
		_merchant.setDayPaidTotalLimit(merchant.getDayPaidTotalLimit());
		_merchant.setDayPaidCountLimit(merchant.getDayPaidCountLimit());
		_merchant.setOrganizeId(merchant.getOrganizeId());
		_merchant.setTranKey(merchant.getTranKey());
		// 开发单位机构号
		if (!PCPSUtil.isEmpty(merchant.getDevelopBranchNo())) {
			_merchant.setDevelopBranchNo(merchant.getDevelopBranchNo());
		}

		// if (!PCPSUtil.isEmpty(merchant.getDepositSaleBranchNo())) {
		// if (saleBranchDaoImpl.getSaleBranchBySaleBranchNo(merchant
		// .getDepositSaleBranchNo()) == null) {
		// throw new OrganApplicationException(
		// OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
		// OrganRespCode.ISSUE_INSERT_UPDATE,
		// "输入的默认充值归属销售机构编号系统不存在!");
		// }
		// }
		if (merchantDaoImpl.IsMerchantName(_merchant.getIssueCompanyNo(),
				_merchant.getMerchantName(), _merchant.getMerchantNo()) > 0) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					merchant.getMerchantName() + ":已经存在");
		}
		// 如果选择允许充值,并且按周期总充值额控制时,充值上限必须>0
		if (merchant.getAllowDeposit().equals("1")
				&& "0".equals(merchant.getDepositLimitType())) {
			if (merchant.getDepositLimit().compareTo(BigInteger.ZERO) <= 0) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"充值额度上限必须大于0");
			}
		}
		_merchant.setDepositSaleBranchNo(merchant.getDepositSaleBranchNo());
		_merchant.setRemark(merchant.getRemark());
		_merchant.setGuaranteeAmount(merchant.getGuaranteeAmount());
		_merchant.setPrepaidLowLimit(merchant.getPrepaidLowLimit());
		// 修改商户信息
		merchantDaoImpl.updateMerchant(_merchant);
		// 插入数据库操作日志
		insertRecordingOperationLog(webInput, "修改商户信息", merchant,
				SysOperLog.operType_Edit, "MerchantName:"
						+ merchant.getMerchantName());
	}

	@Override
	public void deleteMerchant(PCPSWebInput webInput, String merchantNo)
			throws PCPSApplicationException {

	}

	private void insertRecordingOperationLog(PCPSWebInput webInput,
			String logName, Merchant obj, String operType, String lastFieldName)
			throws PCPSApplicationException {
		String logRemark = PCPSUtil.RecordingOperationLog(obj, lastFieldName);
		if (!PCPSUtil.isEmpty(logRemark)) {
			// 插入数据库日志
			SysOperLog sysOperLog = new SysOperLog();
			if (webInput != null && webInput.getOperId() != null) {
				sysOperLog.setOperId(webInput.getOperId());
				sysOperLog.setOperType(operType);
				sysOperLog.setLogName(logName);
				if (webInput != null) {
					sysOperLog.setIpAddress(webInput.getIpAddress());
				}
				if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
					sysOperLog.setIssueCompanyNo(webInput.getOperBranchNo()
							.substring(0, 6));
					sysOperLog.setBranchNo(webInput.getOperBranchNo());
				}
				sysOperLog.setRemark(logRemark);
				sysOperLogDaoImpl.insertSysOperLog(sysOperLog);
			}
		}
	}
}
